package com.cherrish.demo.bio;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.Charset;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author cherrish
 * @time 2019-02-25 10:32
 * @name BiooServer
 * @desc:
 */
public class BiooServer {
    public static void main(String[] args) {
        startServer1(9010);
//        startServer2(9010);
//        startServer3(9010);
    }
    private static void startServer1(int port){
        try (ServerSocket ss = new ServerSocket(port)){
            while (true){
                Socket s = ss.accept();
                System.out.println(s.getInetAddress() + "connected");
                BufferedReader reader = new BufferedReader(new InputStreamReader(s.getInputStream(), Charset.forName("UTF-8")));
                String msg = null;
                while (null != (msg = reader.readLine())){
                    System.out.println(msg);
                }
                s.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    private static void startServer2(int port){
        try (ServerSocket ss = new ServerSocket(port)){
            while (true){
                Socket s = ss.accept();
                System.out.println(s.getInetAddress() + "connected");
                new Thread(new SocketProcess(s)).start();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    static class SocketProcess implements Runnable{
        Socket socket;

        public SocketProcess(Socket socket) {
            this.socket = socket;
        }

        @Override
        public void run() {
            try(BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream(), Charset.forName("UTF-8")))) {
                String msg = null;
                while (null != (msg = reader.readLine())){
                    System.out.println(msg);
                }
            } catch (IOException e) {
                e.printStackTrace();
            } ;
        }
    }

    private static void startServer3(int port){
        ExecutorService tpool = Executors.newFixedThreadPool(100);
        try(ServerSocket ss = new ServerSocket(port);) {
            while (true){
                Socket socket = ss.accept();
                tpool.execute(new SocketProcess(socket));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        tpool.shutdown();
    }
}
